package com.broada.apm.util;

import java.io.File;

import org.apache.tools.ant.util.FileUtils;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.node.NodeBuilder;

public class EmbedESServer {
	
	private static final String DEFAULT_DATA_DIRECTORY = "target/elasticsearch-data";

	private org.elasticsearch.node.Node node ;
	private String dataDirectory;

	public EmbedESServer() {
		this(DEFAULT_DATA_DIRECTORY);
	}

	public EmbedESServer(String dataDirectory) {
		this.dataDirectory = dataDirectory;

		Settings.Builder elasticsearchSettings = Settings.settingsBuilder()
				.put("http.enabled", "true")
				.put("path.home", "...")
				.put("es.cluster.name", "elas.apm")
				.put("network.bind_host", "127.0.0.1")
				.put("http.port", "9200")
				.put("path.data", dataDirectory);

		node = NodeBuilder.nodeBuilder()
				.local(true)
				.settings(elasticsearchSettings.build())
				.node();
	}

	public Client getClient() {
		return node.client();
	}

	public void shutdown() {
		node.close();
		deleteDataDirectory();
	}

	public void deleteDataDirectory() {
		FileUtils.delete(new File(dataDirectory));
	}
	
	public static void main(String[] args) {
		new EmbedESServer().deleteDataDirectory();
	}
}
